#include "customtreecontrol.h"
//#include <QMessageBox>
//#include <QInputDialog>
//#include <QLineEdit>

CustomTreeControl::CustomTreeControl(QWidget *parent)
    : QWidget{parent}
{

    initUi();

}

void CustomTreeControl::initUi()
{

    m_treeView = new  QTreeView(this);
    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(m_treeView);
    layout->setContentsMargins(0,0,0,0);
    this->setLayout(layout);

    m_treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_model = new QStandardItemModel;
    m_model->setHorizontalHeaderLabels({m_treeTitle});
    m_treeView->setModel(m_model);
    createRightPopMenu();
}

void CustomTreeControl::initModel()
{
    if(!m_db.isOpen())
    {
        qDebug()<<"数据库实例初始化失败!"<<m_db.isOpen();
        return;
    }

    loadTreeFromDb(m_model);
    if(m_model->rowCount()==0)
    {
        qDebug()<<"new node";
        addNode(QModelIndex(), "初始节点");
    }
}

void CustomTreeControl::setTreeTitle(QString strTitle)
{
    m_treeTitle = strTitle;
    m_model->setHorizontalHeaderLabels({m_treeTitle});
}

void CustomTreeControl::createRightPopMenu()
{
    // 为TreeView设置右键菜单
    m_contextMenu = new QMenu(this);

    QAction *addActionBrother = m_contextMenu->addAction("新建同级节点");
    addActionBrother->setIcon(QIcon(":Resource/icon/equalizer.svg"));
    QAction *addActionChild = m_contextMenu->addAction("新建子节点");
    addActionChild->setIcon(QIcon(":Resource/icon/delete-two.svg"));
    QAction *delActionCurrent = m_contextMenu->addAction("删除当前节点");
    delActionCurrent->setIcon(QIcon(":Resource/icon/pic.svg"));
    QAction *updActionRename = m_contextMenu->addAction("重命名");
    updActionRename->setIcon(QIcon(":Resource/icon/tool.svg"));
    QAction *ActionReflesh = m_contextMenu->addAction("刷新");
    ActionReflesh->setIcon(QIcon(":Resource/icon/refresh.svg"));

    connect(addActionBrother, &QAction::triggered, this, &CustomTreeControl::slotAddBrotherNode);
    connect(addActionChild, &QAction::triggered, this, &CustomTreeControl::slotAddChildNode);
    connect(delActionCurrent, &QAction::triggered, this, &CustomTreeControl::slotDeleteNode);
    connect(updActionRename, &QAction::triggered, this, &CustomTreeControl::slotModifyNode);
    connect(ActionReflesh, &QAction::triggered, this, &CustomTreeControl::slotRefleshNode);

    // 关键在于在这里处理右键点击事件并显示菜单
    m_treeView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(m_treeView,SIGNAL(customContextMenuRequested(const QPoint &)),this, SLOT(slotCustomContextMenu(const QPoint &)));
    // 当部门节点选中时，更新表格数据
    connect(m_treeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &CustomTreeControl::slotSelectionChanged);

}
void CustomTreeControl::slotCustomContextMenu(const QPoint &point)                     //槽函数定义
{
    QModelIndex index = m_treeView->indexAt(point);
    if (index.isValid()) {
        m_contextMenu->popup(m_treeView->viewport()->mapToGlobal(point));
    }
}
void CustomTreeControl::loadTreeFromDb(QStandardItemModel *model)
{
    QSqlQuery query(m_db);
    query.prepare("SELECT id, name, path FROM custom_tree_control where treetype = ? ORDER BY path");
    query.addBindValue(m_treeType);

    if (query.exec()) {
        QHash<int, QStandardItem*> nodeMap; // 用于保存每个节点ID对应的QStandardItem对象

        while (query.next()) {
            int nodeId = query.value(0).toInt();
            QString nodeName = query.value(1).toString();
            QString nodePath = query.value(2).toString();
            //qDebug()<<nodeName<<nodePath;
            QStringList pathParts = nodePath.split('/');
            QStandardItem *parentItem = nullptr;

            // 获取当前节点的父节点
            for (int i = 1; i < pathParts.size() - 1; ++i)
            {
                int parentId = pathParts[i].toInt();

                if (nodeMap.contains(parentId))
                {
                    parentItem = nodeMap[parentId];
                }
                else
                {
                    qDebug() << "Invalid parent ID detected, skipping node: " << nodeId;
                    continue;
                }
            }

            // 创建并添加新的节点
            QStandardItem *nodeItem = new QStandardItem(nodeName);
            nodeItem->setData(nodeId, Qt::UserRole); // 存储节点ID供后续操作使用
            if (parentItem) {
                nodeItem->setIcon(QIcon(":Resource/icon/bill.svg"));
                parentItem->appendRow(nodeItem);
            } else { // 如果是根节点，将其添加至模型的根项

                nodeItem->setIcon(QIcon(":Resource/icon/bookmark-one.svg"));
                model->invisibleRootItem()->appendRow(nodeItem);

            }

            nodeMap[nodeId] = nodeItem; // 将新节点添加到映射表中
        }
    } else {
        qDebug() << "Failed to execute query: " << query.lastError().text();
    }
}

QString CustomTreeControl::getParentPathFromDb(int parentId)
{
    QSqlQuery query(m_db);
    query.prepare("SELECT path FROM custom_tree_control where treetype = ? and id = ?");
    query.addBindValue(m_treeType);
    query.addBindValue(parentId);

    if (query.exec() && query.next()) {
        return query.value(0).toString();
    } else {
        qDebug() << "Failed to retrieve path for parent ID: " << parentId;
        return "";
    }
}

int CustomTreeControl::insertNodeToDb(const QString nodePath, const QString nodeName)
{
    QSqlQuery insertQuery(m_db);
    insertQuery.prepare("INSERT INTO custom_tree_control (name, path,treetype) VALUES (?,?,?)");
    insertQuery.addBindValue(nodeName);
    insertQuery.addBindValue("-");
    insertQuery.addBindValue(m_treeType);
    if (insertQuery.exec())
    {
        int insertedId = insertQuery.lastInsertId().toInt();
        QString newNodePath = nodePath + '/' + QString::number(insertedId);
        // 更新新节点的完整路径
        QSqlQuery updateQuery(m_db);
        updateQuery.prepare("UPDATE custom_tree_control SET path = ? WHERE id = ? and treetype = ?");
        updateQuery.addBindValue(newNodePath);
        updateQuery.addBindValue(insertedId);
        updateQuery.addBindValue(m_treeType);
        if (updateQuery.exec())
            return insertedId;
        else
        {
            qDebug() << "Failed to update path of new node: " << updateQuery.lastError().text();
            return -1;
        }
    }
    else
    {
        qDebug() << "Failed to insert new node: " << insertQuery.lastError().text();
        return -1;
    }
}

void CustomTreeControl::deleteNodeToDb(int nodeId)
{
    QSqlQuery deleteQuery(m_db);
    QString strSql = "DELETE FROM custom_tree_control WHERE treetype = '"+m_treeType+"' and (path like '%/"+QString::number(nodeId)+"/%') or (path like '%/"+QString::number(nodeId)+"')";
    qDebug()<<strSql;
    deleteQuery.prepare(strSql);
    //deleteQuery.addBindValue(nodeId);
    if (!deleteQuery.exec())
    {
        qDebug() << "Failed to delete Category: " << deleteQuery.lastError().text()<<nodeId;
    }
}

void CustomTreeControl::updateNodeToDb(int nodeId, QString nodeName)
{
    QSqlQuery updateQuery(m_db);
    updateQuery.prepare("UPDATE custom_tree_control SET name = ? WHERE id = ? and treetype = ?");
    updateQuery.addBindValue(nodeName);
    updateQuery.addBindValue(nodeId);
    updateQuery.addBindValue(m_treeType);
    if (!updateQuery.exec())
    {
        qDebug() << "Failed to update TreeNode: " << updateQuery.lastError().text()<<nodeName;
    }
}


void CustomTreeControl::addNode(const QModelIndex &parentIndex, const QString &nodeName)
{
    if(nodeName.isEmpty())
        return;

    if (parentIndex.isValid())// 参数合法性检查
    {
        int parentId = m_model->itemFromIndex(parentIndex)->data(Qt::UserRole ).toInt();
        //qDebug()<<"parentId"<<parentId;

        QString parentPath = getParentPathFromDb(parentId);
        int insertedId = insertNodeToDb(parentPath,nodeName);
        if(insertedId==-1)
            return;
        QStandardItem *parentItem = m_model->itemFromIndex(parentIndex);
        QStandardItem *newItem = new QStandardItem(nodeName);
        newItem->setIcon(QIcon(m_parentIcon));
        newItem->setData(insertedId, Qt::UserRole ); // 存储数据库ID
        parentItem->appendRow(newItem);

    }
    else
    {
        qDebug() << "创建新类别节点";
        //QString rootNodePath = "/";
        int insertedId = insertNodeToDb("",nodeName);
        if(insertedId==-1)
            return;
        // 将数据库变化反映到模型中
        QStandardItem *rootItem = new QStandardItem(nodeName);
        rootItem->setData(insertedId, Qt::UserRole );
        rootItem->setIcon(QIcon(m_childIcon));
        m_model->appendRow(rootItem);
    }
}

void CustomTreeControl::slotRefleshNode()
{
    //加载数据库的节点信息到qtreeview中
//    m_model->clear();
//    m_model->setHorizontalHeaderLabels({"域名类别管理"});
    m_model->removeRows(0,m_model->rowCount());
    loadTreeFromDb(m_model);
}

void CustomTreeControl::slotAddBrotherNode()
{
    QModelIndex selectedIndex = m_treeView->selectionModel()->currentIndex();
    if (!selectedIndex.isValid()) {
        QMessageBox::warning(this, "警告", "请选择一个节点以添加同级节点！");
        return;
    }
    bool ok;
    QString newText = QInputDialog::getText(this,"编辑节点清单名称","请输入新的节点名称:",QLineEdit::Normal,"新节点",&ok);
    if (ok && !newText.isEmpty())
    {
        addNode(selectedIndex.parent(),newText);
    }
}

void CustomTreeControl::slotAddChildNode()
{
    QModelIndex selectedIndex = m_treeView->selectionModel()->currentIndex();
    if (!selectedIndex.isValid()) {
        QMessageBox::warning(this, "警告", "请选择一个节点以添加子节点！");
        return;
    }
    bool ok;
    QString newText = QInputDialog::getText(this,"编辑节点清单名称","请输入新的节点名称:",QLineEdit::Normal,"新节点",&ok);
    if (ok && !newText.isEmpty())
    {
        addNode(selectedIndex,newText);
        //m_treeView->setCurrentIndex(m_domainCategoryModel->index(selectedIndex.row() + 1, 0, selectedIndex.parent()));
    }
}

void CustomTreeControl::slotDeleteNode()
{
    QModelIndex selectedIndex = m_treeView->selectionModel()->currentIndex();
    if (!selectedIndex.isValid()) {
        QMessageBox::warning(this, "警告", "请选择一个节点以删除！");
        return;
    }
    QModelIndex parentIndex = selectedIndex.parent();

    QStandardItemModel *model = static_cast<QStandardItemModel*>(m_treeView->model());
    if(model->rowCount()==1&&!parentIndex.isValid())
    {
        QMessageBox::warning(this, "警告", "最后一个节点不可以删除！");
        return;
    }
    QStandardItem *tItem = model->itemFromIndex(selectedIndex);
    QString infostr = "是否要删除该节点："+tItem->text();

    QMessageBox::StandardButton result= QMessageBox::question(this,"提示",infostr);
    if(result==QMessageBox::Yes)
    {
        int nodeId = tItem->data(Qt::UserRole).toInt();
        deleteNodeToDb(nodeId);
        model->removeRow(selectedIndex.row(), selectedIndex.parent());
        emit treeDeleteNode(nodeId);
    }
}

void CustomTreeControl::slotModifyNode()
{
    QModelIndex selectedIndex = m_treeView->selectionModel()->currentIndex();
    if (!selectedIndex.isValid()) {
        QMessageBox::warning(this, "警告", "请选择一个节点！");
        return;
    }

    QStandardItemModel *model = static_cast<QStandardItemModel *>(m_treeView->model());
    bool ok;
    QString newText = QInputDialog::getText(this,"编辑节点","请输入新的节点文本:",QLineEdit::Normal,model->itemFromIndex(selectedIndex)->text(),&ok);
    if (ok && !newText.isEmpty()) {
        QStandardItem *tItem = model->itemFromIndex(selectedIndex);
        tItem->setText(newText);
         //更新节点信息到数据库
        updateNodeToDb(tItem->data(Qt::UserRole).toInt(),newText);
    }
}

void CustomTreeControl::slotSelectionChanged()
{
    QModelIndex currentSelection = m_treeView->selectionModel()->currentIndex();
    if (currentSelection.isValid())
    {
        QStandardItem *selectItem = m_model->itemFromIndex(currentSelection);
        if(!selectItem->hasChildren())
        {
            int nodeId = selectItem->data(Qt::UserRole).toInt();
            emit treeSelectedChanged(nodeId);
        }
    }

}

